import asyncio
import threading

from fastapi import FastAPI

app = FastAPI()

threads = []


class AsyncThread(threading.Thread):
    def __init__(self, async_callable):
        super().__init__()
        self.loop = asyncio.new_event_loop()
        self.async_callable = async_callable
        # self.daemon = True
        asyncio.set_event_loop(self.loop)
        asyncio.run_coroutine_threadsafe(self.async_callable, self.loop)

    def run(self) -> None:
        self.loop.run_forever()

    def stop(self):
        self.async_callable = lambda: None
        self.loop.stop()


@app.get("/test")
def test():
    async def _test(t):
        await asyncio.sleep(t)
        print(1111)

    thread = AsyncThread(_test(10))
    thread.start()
    threads.append({"name": "t1", "thread": thread})
    print(threads)


@app.get("/stop")
def stop():
    for index, thread in enumerate(threads):
        if thread['name'] == "t1":
            thread['thread'].stop()
            del threads[index]
    print(threading.enumerate())
